import json
import os
from config import BASE_PATH
from multipledispatch import dispatch

"""
    封装一些公共方法
"""


# 读取json数据 方法1
@dispatch(str,str)
def read_json(filename,key)->list:
    filePath = BASE_PATH + os.sep + "data" + os.sep + filename
    with open(filePath,encoding="utf-8") as f:
        #读取json数据
        json_data = json.load(f) #数据转换成 [(),()]
        list = []
        #遍历
        for data in json_data.get(key):
            list.append(tuple(data.values()))
        return list

# 读取json 方法2
@dispatch(str)
def read_json(filename)->list:
    filePath = BASE_PATH + os.sep + "data" + os.sep + filename
    with open(filePath, encoding="utf-8") as f:
        # 读取json数据
        json_data = json.load(f)  # 数据 [[],[]]
        return json_data


# 写入json
def write_json(filename, data):
    filepath = BASE_PATH + os.sep + "data" + os.sep + filename
    with open(filepath, "w", encoding="utf-8")as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

# 字符串截取-用于需要打印长字符串
def str_limit(val,length):
    suffix = "..."
    if length >= len(val):
        result = val
    else:
        result = val[:length] + suffix
    return result

if __name__ == "__main__":
    pass
    # print(str_limit("11111112321333333333",8))
    # print(read_json("parsing.json"))
    # print(read_json("sniffing.json","accessibility"))